package com.example.blogsystem.demos.controller;

import com.example.blogsystem.demos.model.BlogInfo;
import com.example.blogsystem.demos.model.Result;
import com.example.blogsystem.demos.service.BlogService;
import com.example.blogsystem.demos.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/queryBlogList")
    public List<BlogInfo> queryBlogList(){
        List<BlogInfo> res = blogService.queryBlogList();
        return res;
    }

    @RequestMapping("/queryBlogDetail")
    public BlogInfo queryBlogDetail(Integer blogId, HttpServletRequest request){
        BlogInfo blogInfo = blogService.queryBlogDetail(blogId);
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);

        log.info("usrId: " + userId + ", blogId: " + blogInfo.getUserId());
        if (userId != null && userId == blogInfo.getUserId()){
            blogInfo.setAdmin(true);
        }
        return blogInfo;
    }

    @RequestMapping("/publishBlog")
    public Result publishBlog(String title, String content, HttpServletRequest request){
        String token = request.getHeader("user_token");
        Integer userId = JwtUtils.getUserIdFromToken(token);

        if (userId == null || userId < 0){
            log.info("传来的用户id有误，为: " + userId);
            return Result.fail("用户未登录", false);
        }

        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setUserId(userId);
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogService.insertBlog(blogInfo);
        return Result.success(true);
    }

    @RequestMapping("/updateBlog")
    public boolean updateBlog(Integer id, String title, String content){
        BlogInfo blogInfo = new BlogInfo();
        blogInfo.setTitle(title);
        blogInfo.setContent(content);
        blogInfo.setId(id);

        blogService.updateBlog(blogInfo);
        return true;
    }

    @RequestMapping("/deleteBlog")
    public boolean deleteBlog(Integer blogId){
        blogService.deleteBlog(blogId);
        return true;
    }
}
